﻿using jinmaMesProxy.DataAccess;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Net;

namespace jinmaMesProxy.Controllers
{
    public class MyController : ControllerBase
    {
        protected HttpContext httpContext;
        protected ErpDbInstance dbInstance;
        public MyController()
        {
            httpContext = ServiceLoader.GetService<IHttpContextAccessor>().HttpContext!;
            dbInstance = ServiceLoader.GetService<ErpDbInstance>();
            dbInstance.StartTransaction();
            httpContext.Response.OnStarting(Func, httpContext);
        }
        protected Task Func(object obj)
        {
            var context = obj as HttpContext;
            if (context?.Response.StatusCode == (int)HttpStatusCode.OK)
            {
                Commit();
            }
            else
            {
                Abort();
            }
            return Task.CompletedTask;
        }
        protected void Commit()
        {
            this.dbInstance.Commit();
        }
        protected void Abort()
        {
            this.dbInstance.Abort();
        }
    }
}
